import pyodbc
import hashlib


class Database:
    def __init__(self):
        self.connection = None
        self.connect()

    def connect(self):
        try:
            conn_str = (
                "DRIVER={ODBC Driver 17 for SQL Server};"
                "SERVER=LAPTOP-G9HC6J58;"
                "DATABASE=TravelAgency;"
                "UID=sa;"
                "PWD=123456"
            )
            self.connection = pyodbc.connect(conn_str)
            return True
        except Exception as e:
            print(f"无法连接到数据库: {str(e)}")
            return False

    def execute_query(self, query, params=None, fetch=True):
        try:
            cursor = self.connection.cursor()
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)

            if fetch:
                columns = [column[0] for column in cursor.description]
                results = [dict(zip(columns, row)) for row in cursor.fetchall()]
                return results
            else:
                self.connection.commit()
                return cursor.rowcount
        except Exception as e:
            self.connection.rollback()
            print(f"执行查询时出错: {str(e)}")
            return None

    def close(self):
        if self.connection:
            self.connection.close()

    @staticmethod
    def hash_password(password):
        return hashlib.sha256(password.encode()).hexdigest()